<template>
	<view>
		<view class="page_title">
			<view class="page_title_left">{{number_of_diners}}人就餐</view>
			<view class="page_title_right">
				<img src="../../static/tab/share.svg" alt="" class="page_title_right_img"/>
				<img src="../../static/tab/user.svg" alt="" class="page_title_right_img" @click="linkMyOrder"/>
			</view>
			<view class="page_center">
				<view class="page_center_left">
					<scroll-view class="scroll_hei" scroll-y scroll-with-animation enhanced :show-scrollbar="false">
						<view :class="['item_text',{active:index == trigger}]" v-for="(item,index) in categoryList" :key="item.value" @click="handleCategory(index,item.cid)">
							<text>{{item.value}}</text>
							<text class="rotundity" v-if="item.sele_quantity > 0">{{item.sele_quantity}}</text>
						</view>
					</scroll-view>
				</view>
				<view class="page_center_right">
					<scroll-view scroll-y class="scroll_hei" scroll-with-animation  enhanced :show-scrollbar="false" @scroll="getScrollHeight" :scroll-into-view="scroll_into">
						<view v-for="(item,index) in menuList" :key="item.cid" class="category_box" :id="item.cid">
							<view class="page_center_right_title">{{item.category}}</view>
							<view class="page_center_right_main" v-for="(t,i) in item.good_query">
								<img :src="t.image" alt="" class="page_center_right_main_img"/>
								<view class="page_center_right_main_infor">
									<view class="infor_title">{{t.name}}</view>
									<view class="infor_onsell">已售 {{t.monthlysale}}</view>
									<view class="infor_price">
										<view class="infor_price_left">
											<text>￥{{t.unitprice}}</text>
											<text class="infor_price_left_unit">/{{t.unit}}</text>
										</view>
										<view class="infor_price_right">
											<img v-if="t.quantity > 0" src="../../static/tab/add.svg" alt="" class="infor_price_right_img" @click="handleShops(index,i,item.cid,t,'reduce')" />
											<view  v-if="t.quantity > 0" class="infor_price_text">{{t.quantity}}</view>
											<img src="../../static/tab/reduce.svg" alt="" class="infor_price_right_img" @click="handleShops(index,i,item.cid,t)"/>	
										</view>
										
									</view>
								</view>
							</view>
						</view>
						
					</scroll-view>
					
				</view>
			</view>
			<view class="page_bottom" @click="showCar">
				<img src="../../static/tab/shopping_cart.svg" alt=""  class="page_bottom_left" v-if="carList.length"/>
				<img src="../../static/tab/car_g.svg" alt="" class="page_bottom_left" v-else/>
				<text class="rotundity bottom_rot" v-if="carList.length">{{carMenuNum}}</text>
				<view :class="[carList.length ? 'page_bottom_right' :'page_bottom_right_g' ]" @click.stop="subMessage">选好了</view>
			</view>
		</view>
		<car 
			v-if="isShowCar" 
			@hideParentCar='hideCar' 
			@handleCarNum='handleCarlistNum'
			@clearList='clearList'
			:carlist='carList'
			>
		</car>
	</view>
</template>

<script>
	import car from './components/car.vue'
	import { code } from '../../config/order.js'
	import { analysis } from '../../config/data-analysls.js'
	// l连接数据库
	const db = wx.cloud.database()
	const good_collect = db.collection('order_data')
	const dishes_data = db.collection('dishes_data')
	const _ = db.command
	export default {
		components:{car},
	  data() {
	    return {
			categoryList:[],
			menuList:[],
			trigger:0, // 给类目选中样式
			categoryHeightList:[],
			topHeight:0,
			scroll_into:'',
			isShowCar:false,
			carList:[],
			carMenuNum:0,
			number_of_diners:0
	    }
	  },
	  methods: {
		  // 跳转到我的订单
		  linkMyOrder() {
			wx.redirectTo({
				url:'/pages/my-order/my-order'
			})  
		  },
		  // 清空购物车
		  clearList() {
			  this.carList = []
			  this.getdata()
		  },
		  // 修改购物数量
		  handleCarlistNum(data) {
			  let { i, tag, item } = data
			  const newQuantity = tag === 'reduce' ? this.carList[i].quantity - 1 : this.carList[i].quantity + 1
			  const totalPrice =  this.carList[i].quantity * this.carList[i].unitprice
			  this.$set(this.carList[i],'quantity', newQuantity)
			  this.$set(this.carList[i],'totalPrice', totalPrice)
			
			  
			  // 同步menulist
			  const { _id,cid } = item
			  this.updateQuantity(_id,newQuantity,'quantity')
			  this.updateSeleQuantity(cid)
			  
			  
		  },
		  updateQuantity(itemId, newQuantity,tag) {
		      for (let category of this.menuList) {
		          for (let item of category.good_query) {
		              if (item._id === itemId) {
		                  item[tag] = newQuantity;
		                  return true;
		              }
		          }
		      }
		      return false;
		  },
		  updateSeleQuantity(cid) {
			const menu = this.menuList.find(menu => menu.cid === cid);
			if (menu) {
				const seleQuantity = menu.good_query.reduce((total, item) => total + item.quantity, 0);
				this.carMenuNum = seleQuantity
				this.categoryList.map((category,index) => {
					if(category.cid === cid) {
						category.sele_quantity = seleQuantity
					}
				})
			} else {
				console.error("在menuList中未找到匹配的分类项。");
			}
			
			
		  },
		  // 显示购物车
		  showCar() {
			  if(this.carList.length) {
				 this.isShowCar = !this.isShowCar 
			  }else {
				  this.isShowCar= false
			  }
			  
		  },
		  hideCar() {
			  this.isShowCar= false
		  },
		  removeItemById(array, idToRemove) {
		    return array.filter(item => item._id !== idToRemove);
		  },
		  // 构造购物车数据格式
		  getCarData(data) {
			  const isIdenticalID = this.carList.some(item => {
				  return item._id === data._id
			  })
			  if(isIdenticalID && data.quantity) {
				  // 取出最新的添加数量以及总数并更新
				  const { totalPrice, quantity } = data
				  this.carList.forEach((item,index) => {
					  if(item._id === data._id) {
						 this.$set(this.carList[index],'totalPrice',totalPrice)
						 this.$set(this.carList[index],'quantity',quantity)
					  }
				  })
			  }else if(isIdenticalID && !data.quantity) {
				  console.log('jinru');
				  this.carList = this.removeItemById(this.carList,data._id)
				  console.log(this.carList);	
			  }else {
				  this.carList.push(data)
			  }
			  console.log(data.cid,'data.cid');
			  this.updateSeleQuantity(data.cid)
		  },
		  // 增加商品
		  handleShops(index,i,cid,t,tag) {
			  let { quantity,image,name,unitprice, _id} = t
			  const newQuantity = tag ? quantity - 1 : quantity + 1
			  this.$set(this.menuList[index].good_query[i],'quantity',newQuantity)
			  this.$set(this.menuList[index].good_query[i],'sele_quantity',newQuantity)
			  const obj = {
				  image,
				  name,
				  unitprice,
				  quantity:newQuantity,
				  totalPrice:unitprice*newQuantity,
				  cid,
				  _id,
			  }
			  this.getCarData(obj)
			  
		  },
		  getScrollHeight(event) {
			  let scrollTop = event.detail.scrollTop
			  if(scrollTop >= this.topHeight) {
				  // 上拉
				  if(scrollTop >= this.categoryHeightList[this.trigger]) {
					  this.trigger += 1
				  }
			  }else {
				  // 下拉
				  if(scrollTop < this.categoryHeightList[this.trigger - 1]) {
					  this.trigger -= 1
				  }
			  }
			  this.topHeight = scrollTop
		  },
		  // 获取每个分类的高度
		getEveryHeight() {
			let cate_height = 0
			const query = wx.createSelectorQuery()
			query.selectAll('.category_box').boundingClientRect()
			query.exec(res => {
				res[0].forEach(item => {
					cate_height += item.height
					this.categoryHeightList.push(cate_height)
				})
			})
		},
	    async getdata() {
	      try {
	        const res = await wx.cloud.callFunction({name:'Dish-manage',data:{}})
			let {res_cate,res_dis } = res.result
			this.categoryList = res_cate
			console.log(this.categoryList);
	        this.menuList = res_dis
			this.scroll_into = 
			this.$nextTick(() => {
				this.getEveryHeight()
			})
	      } catch (error) {
	        console.error('调用云函数失败：', error)
	      }
	    },
		handleCategory(index,cid) {
			this.trigger = index
			this.scroll_into = cid
				
			setTimeout(() => {
				this.scroll_into = ''
			},200)
		},
		
		
		// 弹出订阅消息
		subMessage() {
			if(this.carList.length) {
				wx.requestSubscribeMessage({
					tmplIds:['kIzp9HPx5XX6lQ-VNJoQQtG7zDDMIhFYVDTAJF5CuU8'],
					success:(res) => {
						this.placeOrder()
					},
					fail:(err)=> {
						this.placeOrder()
						console.log(err,'失败');
					}
				})
			}else{
				return false
			}
			
		},
		// 生成订单
		async placeOrder() {
			const table_number = wx.getStorageSync('table_num')
			wx.showLoading({title:'正在下单',mask:true})
				  let order = {
					  table_number:table_number,
					  number_of_diners:this.number_of_diners,
					  order_time:this.$Time().utcOffset(8).format('YYYY-MM-DD HH:mm:ss'),
					  sett_amount:this.calculateTotalPrice(),
					  order_no:code(),
					  transac_status:'unsettled',
					  order_receiving:'mis_orders',
					  menu:[
						  {
							  backup_data:'备用',
							  goods_list:this.carList
						  }
					  ]
					  
				  }
				  let add_goods = {
					  backup_data:'备用',
					  goods_list:this.carList,
				 }
				  try{
					  
					  // 提交订单要考虑加菜，依据 transac_status 结账状态 以及table_number 
					  let query = await good_collect.where({transac_status:'unsettled',table_number:table_number}).field({_id:true,sett_amount:true}).get()
					  if(query.data.length === 0) {
						  // 第一次或者已经结账
						  const res = await good_collect.add({data:order})
					  }else {
						  // 没有结账，继续加菜
						  let total_amount = Number(query.data[0].sett_amount) + this.calculateTotalPrice()
						  await good_collect.doc(query.data[0]._id).update({
							  data:{
								  sett_amount:total_amount,
								  order_receiving:'mis_orders',
								  menu:_.unshift(add_goods)
							  }
						  })
					  }
					  
					  // 对售出数量进行自增
					  this.carList.forEach(async item => {
						  const res = await dishes_data.doc(item._id).update({
							    data: {
							      monthlysale: item.quantity
							    }
						  })
					  })
					  const time = this.$Time().utcOffset(8).format('YYYY-MM-DD')
					  const totalPrice = this.calculateTotalPrice()
					  // 计算当天的销售额
					  await new analysis().sameday(time,totalPrice)
					  this.push_message()
					  // 页面跳转
					  wx.redirectTo({
						  url:'/pages/order-detail/details'
					  })
					  // 去除loading
					  wx.hideLoading()
					  
				  }catch(e){
					  wx.showToast({
						  title:'发生错误',
						  icon:'error'
					  })
					  console.log(e,'e');
				  }
				  // uni.navigateTo({
				  //     url:'/pages/order-detail/details'
				  // })
		},
		
		
		
		
		// 推送订单提醒
		push_message() {
			this.goEasy.pubsub.publish({
					channel: "test_channel",//替换为您自己的channel
					message: '小程序来的',//替换为您想要发送的消息内容
					onSuccess:res => {
						console.log("消息发布成功。");
					},
					onFailed: function (error) {
						console.log("消息发送失败，错误编码："+error.code+" 错误信息："+error.content);
					}
				})
			
		},
		
		
		// 计算购物车中的总价
		 calculateTotalPrice() {
			 let sett_amount = 0
			 this.carList.map(item => {
				 sett_amount += item.totalPrice
			 })
			 
			 return sett_amount
		 }
		
		
	  },
	  
	  
	  onLoad() {
		  
		  // 获取用餐人数
		this.number_of_diners = wx.getStorageSync('number_of_diners')
	    this.getdata()
	  },
	} 

</script>

<style>
.page_title {
	background: linear-gradient(to bottom,#f7d45f,#f7d562,#f8d561,#f9db76,#f9de80);
	height: 120rpx;
	padding: 0 20rpx;
	display: flex;
	align-items: center;
	position: fixed;
	left:0;
	top:0;
	right: 0;
}
.page_title_right {
	margin-left: auto;
	width: 120rpx;
	display: flex;
	align-items: center;
	justify-content:space-between;
}
.page_title_right_img {
	width: 50rpx;
}
.page_center {
	display: flex;
	position: fixed;
	top:120rpx;
	left:0;
	right:0;
	bottom: 120rpx;
}
.scroll_hei {
	height: 100vh;
}

.page_center_left {
	width: 180rpx;
	background-color: #fafafa;
	overflow-y: auto;
	font-size: 30rpx;
}
.item_text {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 10rpx;
	color:rgba(0,0,0,.5) ;
}
	
.active {
	color:#000 ;
	font-weight: 700;
}
.rotundity {
	margin-left: auto;
	width: 30rpx;
	height: 30rpx;
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 20rpx;
	color: #fff;
	background-color: #eb5941;
}


/* 中部右侧 */
.page_center_right {
	flex:1;
	background-color: #fafafa;
	overflow-y: auto;
}
.page_center_right_title {
	font-size: 28rpx;
	color:#ccc;
	padding: 20rpx 30rpx;
	
}
.page_center_right_main {
	display: flex;
	margin-top: 10rpx;
}
.page_center_right_main_img {
	width: 150rpx;
	height: 150rpx;
	border-radius: 10rpx;
}
.page_center_right_main_infor {
	flex:1;
	font-size: 20rpx;
	padding:0 20rpx;
}
.infor_title {
	color: #000;
	font-size: 30rpx;
	font-weight: 600;
}
.infor_onsell {
	color:#ccc;
	font-size: 26rpx;
	padding-top: 5rpx;
}
.infor_price {
	display: flex;
	align-items: center;
}
.infor_price_left {
	color: #000;
	font-size: 30rpx;
	font-weight: 600;
	padding-top: 10rpx;
}
.infor_price_left_unit {
	color: #ccc;
	font-size: 20rpx;
}
.infor_price_right {
	margin-left:auto;
	display: flex;
	align-items: center;
}
.infor_price_right_img {
	width: 50rpx;
	height: 50rpx;
}
.infor_price_text {
	color: #000;
	font-size: 30rpx;
	font-weight: 600;
	padding: 0 40rpx;
}


















	
.page_bottom {
	position: fixed;
	left:0;
	bottom:0;
	right: 0;
	padding: 0 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 120rpx;
}
	
.page_bottom_left {
	width: 70rpx;
}
	
.page_bottom_right {
	display: flex;
	justify-content: center;
	width: 200rpx;
	height: 90rpx;
	line-height: 90rpx;
	border-radius: 20rpx;
	background-color: #f7d45f;
}
.page_bottom_right_g {
	display: flex;
	justify-content: center;
	width: 200rpx;
	height: 90rpx;
	line-height: 90rpx;
	border-radius: 20rpx;
	background-color: #ccc;
}


.bottom_rot {
	position: fixed;
	left:80rpx;
	bottom:80rpx;
}






::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
}
.scroll-view::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
}
</style>
